<?php

namespace app\admin\controller\zbtask;

use app\admin\logic\DelLogic;
use app\admin\logic\ImportMoney;
use app\admin\logic\TaskLogic;
use app\common\controller\Backend;
use app\common\model\Area;
use app\common\utils\Utils;
use MongoDB\BSON\Type;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Model;

/**
 * 任务
 *f
 * @icon fa fa-circle-o
 */
class Zbtask extends Backend
{
    //数据限制
    protected $dataLimit = 'auth';
    protected $dataLimitFieldAutoFill = false;
    protected $dataLimitField = 'company_id';

    /**
     * 获取数据限制的管理员ID
     * 禁用数据限制时返回的是null
     * @return mixed
     */
    protected function getDataLimitAdminIds()
    {
        if (!$this->dataLimit) {
            return null;
        }

        //超级管理员
        if ($this->auth->isSuperAdmin() || TYPE == 0) {
            return null;
        }
        if (TYPE == 2) {
            $this->error('无权限浏览');
        }
        $company_id = [TYPE_ID];
        return $company_id;
    }
    /**
     * Zbtask模型对象
     * @var \app\common\model\zbtask\Zbtask
     */
    protected $model = null;
    protected $multiFields = 'status,shutdownswitch';
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\zbtask\Zbtask;
        $this->view->assign("shutdownswitchList", $this->model->getShutdownswitchList());
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("typeList", $this->model->getTypeList());
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        $this->searchFields = 'id,name,zbcategory.name,company.name';
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->with(['company','zbcategory'])
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->with(['company','zbcategory'])
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                $row->visible(['id','name','createtime','zbcategory_id','remark','company_id','image','shutdownswitch','status','type', 'is_process']);
                $row->visible(['company']);
				$row->getRelation('company')->visible(['id','name']);
				$row->visible(['zbcategory']);
				$row->getRelation('zbcategory')->visible(['id','name']);
				$filecount = Db::name('zbtask_importlog')->where(['task_id'=> $row['id'], 'type' => 0])->count();
				if ($filecount > 0) {
                    $row['is_process'] = 1;
                } else {
                    $row['is_process'] = 0;
                }
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    public function upload() {
        $task_id = input('task_id/d', 0);
        $type = input('type/d', 0); //0为稍处理  1为立即导入
        if ($this->request->isAjax()) {
            $file = input('image', '');
            if (empty($file)) {
                $this->error('上传文件错误');
            }
            if (!$task_id) {
                $this->error('必须选择某一个任务');
            }
            $ma_data = [
                'file' => $file,
                'task_id' => $task_id
            ];
            $objFanout = new ImportMoney();
            if ($type == 1) {
                try {
                    $objFanout->import($file,$task_id);
                } catch (\Exception $e) {
                    $this->error($e->getMessage());
                }
            } else {
                if ($objFanout->fileLog($file, $task_id)) {
                    $objFanout->publisher(json_encode($ma_data));
                } else {
                    $this->error('导入出现问题');
                }
            }

            $this->success('导入成功');
        }

        //查看导入历史
        $history = Db::name('zbtask_importlog')->where(['task_id' => $task_id])->order('id asc')->select();
        $this->assign('history', $history);
        $this->assign('task_id', $task_id);
        return $this->view->fetch();
    }

    public function add()
    {

        if (!$this->request->isAjax()) {
            $template_id = input('template_id/d', 0);
            if ($template_id) {
                $tin = \app\common\model\zbtask\Template::get($template_id);
                $this->assign('info', $tin);
            } else {
                $this->assign('info', []);
            }
        } else {
            $post = $this->request->post();
            $createtime = input('row.createtime', time());
            $post['row']['createtime'] = strtotime($createtime);
            if (TYPE == 1) {
                $post['row']['company_id'] = TYPE_ID;
            }
            if (TYPE == 0) {
                $post['row']['type'] = 1;
            }
            $this->request->post($post);
        }
        return parent::add();
    }
  /*  public function edit($ids = null)
    {
        $post = $this->request->post();
        $createtime = input('row.createtime', time());
        $post['row']['createtime'] = strtotime($createtime);

        if (TYPE == 1) {
            $post['row']['company_id'] = TYPE_ID;
            $this->noAuth($ids);
        }

        $this->request->post($post);
        return parent::edit($ids);
    }*/
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $createtime = input('row.createtime', Utils::time_format(time()));
            $params['createtime'] = strtotime($createtime);

            if (TYPE == 1) {
                $params['company_id'] = TYPE_ID;
                $this->noAuth($ids);
            }
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    //修改
                    TaskLogic::instance()->edit($ids, $params['createtime']);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 详情
     */
    public function detail($ids)
    {
        $row = $this->model->with(['company','zbcategory'])->find(['id' => $ids]);
        if (!$row)
            $this->error(__('No Results were found'));
        if ($this->request->isAjax()) {
            $this->success("Ajax请求成功", null, ['id' => $ids]);
        }

        $row->visible(['id','area_str','content','type','name','introduce','createtime','zbcategory_id','company_id','province','city','area','image','shutdownswitch','weigh','status']);
        $row->visible(['company']);
        $row->getRelation('company')->visible(['id','name']);
        $row->visible(['zbcategory']);
        $row->getRelation('zbcategory')->visible(['id','type','name']);
        $province = Area::where(['id'=>$row->province])->value('name');
        $city = Area::where(['id'=>$row->city])->value('name');
        $area = Area::where(['id'=>$row->area])->value('name');

        $area_str = $province;
        if ($city) {
            $area_str = $area_str.'/'.$city;
            if ($area) {
                $area_str = $area_str.'/'.$area;
            }
        }
        $row->area_str = $area_str;
        $this->view->assign("row", $row->toArray());
        return $this->view->fetch();
    }

    //审核
    public function check() {
        $ids = $this->request->param('ids/d', 0);
        $type = $this->request->param('type/d', 0);
        $remark = $this->request->param('remark/s', '');

        if (!in_array($type, [1, 2]) || $ids === 0) {
            $this->error('参数错误');
        }

        if (!$remark) {
            //确认派单之后 把订单状态改为处理中   决绝之后  订单变为无效
            $remark = $type == 1 ? '任务审核通过':'任务审核驳回';
        }

        $this->model->where(['id'=>$ids])->update(['type' => $type, 'remark'=> $remark]);

        $this->success('审核成功');
    }

    /**
     * 权限限制
     * @param mixed $param 模型对象或者id
     * @return boolean
     */
    private function noAuth($param) {
        if ($this->request->isPost()) {
            if (!$param instanceof Model) {
                $param = $this->model->get($param);
            }

            if ($param['type'] == 1 && TYPE == 1) {
                $this->error('任务已经审核通过不能操作,操作请联系管理员');
            }
        }

        return true;
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {

        if ($ids) {
            //开启了数据限制 只能删除和查询自己的 如果是管理员 都可以删除
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where('id', 'in', $ids)->select();

            $count = 0;
            foreach ($list as $k => $v) {
                $this->noAuth($v);
                Db::startTrans();
                try {
                    DelLogic::instance()->task($v);  //删除逻辑
                    $count += $v->delete();
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
}
